package net.jgrm.order.controller;

import net.jgrm.order.entity.Order;
import net.jgrm.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 分布式事务测试控制器
 */
@RestController
@RequestMapping("/seata-test")
public class SeataTestController {

    @Autowired
    private IOrderService orderService;

    /**
     * 测试Feign调用的分布式事务
     * 正常情况测试
     */
    @PostMapping("/order/feign")
    public Order createOrderWithFeign(@RequestParam Long userId,
                                      @RequestParam Long productId,
                                      @RequestParam Integer quantity) {
        try {
            return orderService.createOrderWithFeign(userId, productId, quantity);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 测试Dubbo调用的分布式事务
     * 正常情况测试
     */
    @PostMapping("/order/dubbo")
    public Order createOrderWithDubbo(@RequestParam Long userId,
                                      @RequestParam Long productId,
                                      @RequestParam Integer quantity) {
        try {
            return orderService.createOrderWithDubbo(userId, productId, quantity);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 测试分布式事务回滚
     * 通过传入错误的参数来触发异常，验证事务回滚
     */
    @PostMapping("/order/rollback-test")
    public String testRollback(@RequestParam Long userId,
                               @RequestParam Long productId,
                               @RequestParam Integer quantity) {
        try {
            // 故意创建一个会失败的订单来测试回滚
            orderService.createOrderWithFeign(userId, productId, quantity);
            return "订单创建成功";
        } catch (Exception e) {
            return "订单创建失败，事务已回滚：" + e.getMessage();
        }
    }
}